package com.hutou.chuangke.fragmentnet;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.FriendBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.activity.UserInfoActivity;
import com.hutou.chuangke.fragment.AttachFragment;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.widget.CircleImageView;
import com.hutou.chuangke.widget.DividerItemDecoration;
import com.hutou.chuangke.widget.SwipeRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

/**
 * Created by tyhdark on 2017/3/18.
 * 好友列表fragment
 */
public class FriendsListFragment extends AttachFragment{
    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView friend_recyclerviewew;
    private ArrayList<FriendBean> mData = new ArrayList<>();
    private FriendAdapter adapter;
    private boolean isFirst = true;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friendslist,null);
        return view;
    }

    @Override
    public void onViewCreated(View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isAdded()){
            if(isVisibleToUser&&isFirst){
                isFirst = false;
                initData();
            }
        }
    }

    private void initData() {
        loadData();
    }

    private void init(View view) {
        friend_recyclerviewew = (RecyclerView) view.findViewById(R.id.friend_recyclerviewew);
        friend_recyclerviewew.setLayoutManager(new LinearLayoutManager(getActivity()));
        friend_recyclerviewew.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST));
        adapter = new FriendAdapter();
        friend_recyclerviewew.setAdapter(adapter);
        adapter.setonItemListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("userid",mData.get(position).getTargetuserid());
                intent.putExtra("ismyself",false);
                startActivity(intent);
            }
        });
        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
        swipeRefresh.setHeaderView(crateHeadview());
        swipeRefresh.setFooterView(crateHeadview());
        swipeRefresh.setOnPullRefreshListener(new SwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefresh.setRefreshing(true);
                loadData();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefresh.setRefreshing(false);
                    }
                },2000);
            }

            @Override
            public void onPullDistance(int distance) {}

            @Override
            public void onPullEnable(boolean enable) {}
        });

        swipeRefresh.setOnPushLoadMoreListener(new SwipeRefreshLayout.OnPushLoadMoreListener() {
            @Override
            public void onLoadMore() {
                swipeRefresh.setLoadMore(true);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefresh.setLoadMore(false);
                    }
                },2000);
            }

            @Override
            public void onPushDistance(int distance) {

            }

            @Override
            public void onPushEnable(boolean enable) {

            }
        });

    }

    private void loadData(){
        new AsyncTask<Void,Void,Integer>(){

            @Override
            protected Integer doInBackground(Void... voids) {
                int msg = 0;
                try{
                    mData.clear();
                    JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.getfans(MainApplication.id,1,20)
                            ,mContext,false);
                    JsonArray fansarray = jsonObject.get("fansList").getAsJsonArray();
                    for(JsonElement element : fansarray){
                        mData.add(MainApplication.gsonInstance().fromJson(element, FriendBean.class));
                    }

                }catch(Exception e){
                    e.printStackTrace();
                    return 0;
                }
                return msg;
            }

            @Override
            protected void onPostExecute(Integer msg) {
                super.onPostExecute(msg);
                adapter.setData(mData);
                adapter.notifyDataSetChanged();
            }
        }.execute();

    }

    private View crateHeadview() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.loading_circle,null);
        return view;
    }

    Handler handler = new Handler();

    public interface OnItemClickListener{
        void onItemClick(View view,int position);
    }

    class FriendAdapter extends RecyclerView.Adapter<FriendAdapter.ViewHolder>{
        private ArrayList<FriendBean> mData = new ArrayList<>();
        private OnItemClickListener mOnItemClickListener;
        public void setonItemListener(OnItemClickListener mOnItemClickListener){
            this.mOnItemClickListener = mOnItemClickListener;
        }
        @Override
        public FriendAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            FriendAdapter.ViewHolder holder = new FriendAdapter.ViewHolder(LayoutInflater.from(getActivity())
                    .inflate(R.layout.item_friend,null));
            return holder;
        }

        @Override
        public void onBindViewHolder(final FriendAdapter.ViewHolder holder, int position) {
            holder.isfollow_tv.setVisibility(View.GONE);
            holder.name_tv.setText(mData.get(position).getNickname());
            if(mData.get(position).getSex().equals("m")){
                holder.sex_iv.setImageDrawable(getResources().getDrawable(R.drawable.me_male));
            }else{
                holder.sex_iv.setImageDrawable(getResources().getDrawable(R.drawable.me_female));
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, pos);
                }
            });
            ImageLoader.getInstance().displayImage(mData.get(position).getUserimgurl(), holder.headiv);
        }

        public void setData(ArrayList<FriendBean> mData){
            this.mData = mData;
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            TextView name_tv,isfollow_tv;
            ImageView headiv,sex_iv;
            public ViewHolder(View view) {
                super(view);
                name_tv = (TextView) view.findViewById(R.id.name_tv);
                headiv = (CircleImageView) view.findViewById(R.id.headiv);
                sex_iv = (ImageView) view.findViewById(R.id.sex_iv);
                isfollow_tv = (TextView) view.findViewById(R.id.isfollow_tv);
            }
        }
    }
}
